<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.json',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="nsq 介绍nsq是一个基于Go语言的分布式实时消息平台，nsq可用于大规模系统中的实时消息服务，并且每天能够处理数亿级别的消息，其设计目标是为在分布式环境下运行的去中心化服务提供一个强大的基础架构。 nsq具有分布式、去中心化的拓扑结构，该结构具有无单点故障、故障容错、高可用性以及能够保证消息的可靠传递的特征。NSQ非常容易配置和部署，且具有最大的灵活性，支持众多消息协议。另外，官方还提供了拆箱">
<meta name="keywords" content="golang,nsq">
<meta property="og:type" content="article">
<meta property="og:title" content="nsq介绍和go-nsq使用">
<meta property="og:url" content="https://unix2dos.github.io/p/17c769c4.html">
<meta property="og:site_name" content="Levon&#39;s Blog">
<meta property="og:description" content="nsq 介绍nsq是一个基于Go语言的分布式实时消息平台，nsq可用于大规模系统中的实时消息服务，并且每天能够处理数亿级别的消息，其设计目标是为在分布式环境下运行的去中心化服务提供一个强大的基础架构。 nsq具有分布式、去中心化的拓扑结构，该结构具有无单点故障、故障容错、高可用性以及能够保证消息的可靠传递的特征。NSQ非常容易配置和部署，且具有最大的灵活性，支持众多消息协议。另外，官方还提供了拆箱">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-09-27T15:36:51.102Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="nsq介绍和go-nsq使用">
<meta name="twitter:description" content="nsq 介绍nsq是一个基于Go语言的分布式实时消息平台，nsq可用于大规模系统中的实时消息服务，并且每天能够处理数亿级别的消息，其设计目标是为在分布式环境下运行的去中心化服务提供一个强大的基础架构。 nsq具有分布式、去中心化的拓扑结构，该结构具有无单点故障、故障容错、高可用性以及能够保证消息的可靠传递的特征。NSQ非常容易配置和部署，且具有最大的灵活性，支持众多消息协议。另外，官方还提供了拆箱">
  <link rel="canonical" href="https://unix2dos.github.io/p/17c769c4">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>nsq介绍和go-nsq使用 | Levon's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Levon's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">微信:  L6241425</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>时光</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://unix2dos.github.io/p/17c769c4.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Levon">
      <meta itemprop="description" content="Never Give Up">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Levon's Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">nsq介绍和go-nsq使用

          
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2018-05-19 11:01:13" itemprop="dateCreated datePublished" datetime="2018-05-19T11:01:13+08:00">2018-05-19</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-09-27 23:36:51" itemprop="dateModified" datetime="2019-09-27T23:36:51+08:00">2019-09-27</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/1-编程语言/" itemprop="url" rel="index"><span itemprop="name">1-编程语言</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/1-编程语言/golang/" itemprop="url" rel="index"><span itemprop="name">golang</span></a></span>

                
                
              
            </span>
          

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
        
      
      <span class="post-meta-item-text">Disqus：</span>
    
    <a title="disqus" href="/p/17c769c4.html#comments" itemprop="discussionUrl"><span class="post-comments-count disqus-comment-count" data-disqus-identifier="p/17c769c4.html" itemprop="commentCount"></span></a>
  </span>
  
  
          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              
                <span class="post-meta-item-text">本文字数：</span>
              
              <span>5.2k</span>
            </span>
          
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              
              <span>5 分钟</span>
            </span>
          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="nsq-介绍"><a href="#nsq-介绍" class="headerlink" title="nsq 介绍"></a>nsq 介绍</h3><p><a href="https://github.com/bitly/nsq" target="_blank" rel="noopener">nsq</a>是一个基于Go语言的分布式实时消息平台，nsq可用于大规模系统中的实时消息服务，并且每天能够处理数亿级别的消息，其设计目标是为在分布式环境下运行的去中心化服务提供一个强大的基础架构。</p>
<p>nsq具有分布式、去中心化的拓扑结构，该结构具有无单点故障、故障容错、高可用性以及能够保证消息的可靠传递的特征。NSQ非常容易配置和部署，且具有最大的灵活性，支持众多消息协议。另外，官方还提供了拆箱即用Go和Python库。如果读者兴趣构建自己的客户端的话，还可以参考官方提供的<a href="http://nsq.io/clients/tcp_protocol_spec.html" target="_blank" rel="noopener">协议规范</a>。</p>
<p>nsq是由四个重要组件构成：</p>
<ul>
<li><a href="http://bitly.github.io/nsq/components/nsqd.html" target="_blank" rel="noopener">nsqd</a>：一个负责接收、排队、转发消息到客户端的守护进程</li>
<li><a href="http://bitly.github.io/nsq/components/nsqlookupd.html" target="_blank" rel="noopener">nsqlookupd</a>：管理拓扑信息并提供最终一致性的发现服务的守护进程</li>
<li><a href="http://bitly.github.io/nsq/components/nsqadmin.html" target="_blank" rel="noopener">nsqadmin</a>：一套Web用户界面，可实时查看集群的统计数据和执行各种各样的管理任务</li>
<li><a href="http://nsq.io/components/utilities.html" target="_blank" rel="noopener">utilities</a>：常见基础功能、数据流处理工具，如nsq_stat、nsq_tail、nsq_to_file、nsq_to_http、nsq_to_nsq、to_nsq</li>
</ul>
<p>nsq的主要特点如下:</p>
<ul>
<li>具有分布式且无单点故障的拓扑结构 支持水平扩展，在无中断情况下能够无缝地添加集群节点</li>
<li>低延迟的消息推送，参见官方提供的<a href="http://nsq.io/overview/performance.html" target="_blank" rel="noopener">性能说明文档</a></li>
<li>具有组合式的负载均衡和多播形式的消息路由</li>
<li>既擅长处理面向流（高吞吐量）的工作负载，也擅长处理面向Job的（低吞吐量）工作负载</li>
<li>消息数据既可以存储于内存中，也可以存储在磁盘中</li>
<li>实现了生产者、消费者自动发现和消费者自动连接生产者，参见nsqlookupd</li>
<li>支持安全传输层协议（TLS），从而确保了消息传递的安全性</li>
<li>具有与数据格式无关的消息结构，支持JSON、Protocol Buffers、MsgPacek等消息格式</li>
<li>非常易于部署（几乎没有依赖）和配置（所有参数都可以通过命令行进行配置）</li>
<li>使用了简单的TCP协议且具有多种语言的客户端功能库</li>
<li>具有用于信息统计、管理员操作和实现生产者等的HTTP接口</li>
<li>为实时检测集成了统计数据收集器<a href="https://github.com/etsy/statsd/" target="_blank" rel="noopener">StatsD</a></li>
<li>具有强大的集群管理界面，参见nsqadmin</li>
</ul>
<a id="more"></a>

<h3 id="nsqlookupd-中心管理服务-4160-4161"><a href="#nsqlookupd-中心管理服务-4160-4161" class="headerlink" title="nsqlookupd(中心管理服务)  4160 4161"></a>nsqlookupd(中心管理服务)  4160 4161</h3><ol start="0">
<li><p>nsqlookupd是守护进程负责管理拓扑信息。客户端通过查询 nsqlookupd 来发现指定话题（topic）的生产者，并且 nsqd 节点广播话题（topic）和通道（channel）信息</p>
</li>
<li><p>简单的说nsqlookupd就是中心管理服务，它使用tcp(默认端口4160)管理nsqd服务，使用http(默认端口4161)管理nsqadmin服务。同时为客户端提供查询功能</p>
</li>
<li><p>nsqlookupd具有以下功能或特性</p>
</li>
</ol>
<ul>
<li>唯一性，在一个Nsq服务中只有一个nsqlookupd服务。当然也可以在集群中部署多个nsqlookupd，但它们之间是没有关联的</li>
<li>去中心化，即使nsqlookupd崩溃，也会不影响正在运行的nsqd服务</li>
<li>充当nsqd和naqadmin信息交互的中间件</li>
<li>提供一个http查询服务，给客户端定时更新nsqd的地址目录 </li>
</ul>
<h3 id="nsqadmin-展示数据"><a href="#nsqadmin-展示数据" class="headerlink" title="nsqadmin(展示数据)"></a>nsqadmin(展示数据)</h3><ol start="0">
<li>是一套 WEB UI，用来汇集集群的实时统计，并执行不同的管理任务</li>
<li>nsqadmin具有以下功能或特性<ul>
<li>提供一个对topic和channel统一管理的操作界面以及各种实时监控数据的展示，界面设计的很简洁，操作也很简单</li>
<li>展示所有message的数量，恩….装X利器</li>
<li>能够在后台创建topic和channel，这个应该不常用到</li>
<li>nsqadmin的所有功能都必须依赖于nsqlookupd，nsqadmin只是向nsqlookupd传递用户操作并展示来自nsqlookupd的数据</li>
</ul>
</li>
</ol>
<h3 id="nsqd-真正干活的-4150-4151"><a href="#nsqd-真正干活的-4150-4151" class="headerlink" title="nsqd (真正干活的)  4150 4151"></a>nsqd (真正干活的)  4150 4151</h3><ol>
<li>nsqd 是一个守护进程，负责接收，排队，投递消息给客户端</li>
<li>简单的说，真正干活的就是这个服务，它主要负责message的收发，队列的维护。nsqd会默认监听一个tcp端口(4150)和一个http端口(4151)以及一个可选的https端口</li>
<li>nsqd 具有以下功能或特性</li>
</ol>
<ul>
<li>对订阅了同一个topic，同一个channel的消费者使用负载均衡策略（不是轮询）</li>
<li>只要channel存在，即使没有该channel的消费者，也会将生产者的message缓存到队列中（注意消息的过期处理）</li>
<li>保证队列中的message至少会被消费一次，即使nsqd退出，也会将队列中的消息暂存磁盘上(结束进程等意外情况除外)</li>
<li>限定内存占用，能够配置nsqd中每个channel队列在内存中缓存的message数量，一旦超出，message将被缓存到磁盘中</li>
<li>topic，channel一旦建立，将会一直存在，要及时在管理台或者用代码清除无效的topic和channel，避免资源的浪费</li>
</ul>
<h4 id="消费者"><a href="#消费者" class="headerlink" title="消费者"></a>消费者</h4><p>消费者有两种方式与nsqd建立连接</p>
<ul>
<li>消费者直连nsqd，这是最简单的方式，缺点是nsqd服务无法实现动态伸缩了(当然，自己去实现一个也是可以的)  </li>
<li>消费者通过http查询nsqlookupd获取该nsqlookupd上所有nsqd的连接地址，然后再分别和这些nsqd建立连接(官方推荐的做法)，但是客户端会不停的向nsqlookupd查询最新的nsqd地址目录(不喜欢用http轮询这种方式…)</li>
</ul>
<h4 id="生产者"><a href="#生产者" class="headerlink" title="生产者"></a>生产者</h4><p>生产者必须直连nsqd去投递message(网上说，可以连接到nsqlookupd，让nsqlookupd自动选择一个nsqd去完成投递，但是我用Producer的tcp是连不上nsqlookupd的，不知道http可不可以…)，</p>
<p>这里有一个问题就是如果生产者所连接的nsqd炸了，那么message就会投递失败，所以在客户端必须自己实现相应的备用方案</p>
<ul>
<li><p>Producer断线后不会重连，需要自己手动重连，Consumer断线后会自动重连</p>
</li>
<li><p>Consumer的重连时间配置项有两个功能(这个设计必须吐槽一下，分开配置更好一点)</p>
<ul>
<li>Consumer检测到与nsqd的连接断开后，每隔x秒向nsqd请求重连</li>
<li>Consumer每隔x秒，向nsqlookud进行http轮询，用来更新自己的nsqd地址目录</li>
<li>Consumer的重连时间默认是60s(…菜都凉了)，我改成了1s</li>
</ul>
</li>
<li><p>Consumer可以同时接收不同nsqd node的同名topic数据，为了避免混淆，就必须在客户端进行处理</p>
</li>
<li><p>在AddConurrentHandlers和 AddHandler中设置的接口回调是在另外的goroutine中执行的</p>
</li>
<li><p>Producer不能发布(Publish)空message，否则会导致panic</p>
</li>
</ul>
<h3 id="nsq-操作"><a href="#nsq-操作" class="headerlink" title="nsq 操作"></a>nsq 操作</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">brew install nsq</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">nsqlookupd</span><br><span class="line"></span><br><span class="line">[nsqlookupd] 2018/01/24 10:33:31.710309 nsqlookupd v1.0.0-compat (built w/go1.9.1)</span><br><span class="line">[nsqlookupd] 2018/01/24 10:33:31.710772 TCP:</span><br><span class="line">listening on [::]:4160  --nsqd</span><br><span class="line">[nsqlookupd] 2018/01/24 10:33:31.710772 HTTP: </span><br><span class="line">listening on [::]:4161 --nsqadmin</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">nsqd --lookupd-tcp-address=127.0.0.1:4160 -broadcast-address=127.0.0.1</span><br><span class="line"></span><br><span class="line">[nsqd] 2018/01/24 10:35:01.975420 nsqd v1.0.0-compat (built w/go1.9.1)</span><br><span class="line">[nsqd] 2018/01/24 10:35:01.975521 ID: 660</span><br><span class="line">[nsqd] 2018/01/24 10:35:01.975567 NSQ: persisting topic/channel metadata to nsqd.dat</span><br><span class="line">[nsqd] 2018/01/24 10:35:01.976544 TCP: </span><br><span class="line">listening on [::]:4150  --tcp监听4150</span><br><span class="line">[nsqd] 2018/01/24 10:35:01.976597 HTTP: </span><br><span class="line">listening on [::]:4151  --http监听4151</span><br><span class="line">[nsqd] 2018/01/24 10:35:01.976785 LOOKUP(127.0.0.1:4160): adding peer</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">nsqadmin --lookupd-http-address=127.0.0.1:4161</span><br><span class="line"></span><br><span class="line">[nsqadmin] 2018/01/24 10:35:40.562980 nsqadmin v1.0.0-compat (built w/go1.9.1)</span><br><span class="line">[nsqadmin] 2018/01/24 10:35:40.563388 HTTP: </span><br><span class="line">listening on [::]:4171 --监听4171</span><br></pre></td></tr></table></figure>

<h4 id="use"><a href="#use" class="headerlink" title="use"></a>use</h4><p>可以用浏览器访问 <a href="http://127.0.0.1:4171/" target="_blank" rel="noopener">http://127.0.0.1:4171/</a> 观察数据<br>也可尝试下 watch -n 0.5 “curl -s <a href="http://127.0.0.1:4151/stats&quot;" target="_blank" rel="noopener">http://127.0.0.1:4151/stats&quot;</a> 监控统计数据(4151是nsqd的http)</p>
<p>发布一个消息<br>curl -d ‘hello world 1’ ‘<a href="http://127.0.0.1:4151/pub?topic=test&#39;" target="_blank" rel="noopener">http://127.0.0.1:4151/pub?topic=test&#39;</a></p>
<p>创建一个消费者:<br>nsq_to_file –topic=test –output-dir=/tmp –lookupd-http-address=127.0.0.1:4161</p>
<p>再发布几个消息</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">curl -d &apos;hello world 2&apos; &apos;http://127.0.0.1:4151/pub?topic=test&apos;</span><br><span class="line">curl -d &apos;hello world 3&apos; &apos;http://127.0.0.1:4151/pub?topic=test&apos;</span><br></pre></td></tr></table></figure>

<h3 id="go-nsq-使用"><a href="#go-nsq-使用" class="headerlink" title="go-nsq 使用"></a>go-nsq 使用</h3><p>运行之前, 保证 nsqd 在运行</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">import (</span><br><span class="line">	&quot;log&quot;</span><br><span class="line">	&quot;time&quot;</span><br><span class="line"></span><br><span class="line">	nsq &quot;github.com/bitly/go-nsq&quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">	go startConsumer()</span><br><span class="line">	startProducer()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 生产者</span><br><span class="line">func startProducer() &#123;</span><br><span class="line">	cfg := nsq.NewConfig()</span><br><span class="line">	producer, err := nsq.NewProducer(&quot;127.0.0.1:4150&quot;, cfg)</span><br><span class="line">	if err != nil &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line">	// 发布消息</span><br><span class="line">	for &#123;</span><br><span class="line">		if err := producer.Publish(&quot;test&quot;, []byte(&quot;test message&quot;)); err != nil &#123;</span><br><span class="line">			log.Fatal(&quot;publish error: &quot; + err.Error())</span><br><span class="line">		&#125;</span><br><span class="line">		time.Sleep(1 * time.Second)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 消费者</span><br><span class="line">func startConsumer() &#123;</span><br><span class="line">	cfg := nsq.NewConfig()</span><br><span class="line">	consumer, err := nsq.NewConsumer(&quot;test&quot;, &quot;sensor01&quot;, cfg)</span><br><span class="line">	if err != nil &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line">	// 设置消息处理函数</span><br><span class="line">	consumer.AddHandler(nsq.HandlerFunc(func(message *nsq.Message) error &#123;</span><br><span class="line">		log.Println(string(message.Body))</span><br><span class="line">		return nil</span><br><span class="line">	&#125;))</span><br><span class="line">	// 连接到单例nsqd</span><br><span class="line">	if err := consumer.ConnectToNSQD(&quot;127.0.0.1:4150&quot;); err != nil &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line">	&lt;-consumer.StopChan</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    
        
      
        <div id="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作, 一个耿直的笑脸~</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Levon 微信支付">
        <p>微信支付</p>
      </div>
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="Levon 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/golang/" rel="tag"># golang</a>
            
              <a href="/tags/nsq/" rel="tag"># nsq</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/p/127812f2.html" rel="next" title="golang_ide_vscode的使用调试和问题解决">
                  <i class="fa fa-chevron-left"></i> golang_ide_vscode的使用调试和问题解决
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/p/63c8f369.html" rel="prev" title="golang_context包的介绍和使用">
                  golang_context包的介绍和使用 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    
  <div class="comments" id="comments">
    <div id="disqus_thread">
      <noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
    </div>
  </div>
  
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#nsq-介绍"><span class="nav-number">1.</span> <span class="nav-text">nsq 介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#nsqlookupd-中心管理服务-4160-4161"><span class="nav-number">2.</span> <span class="nav-text">nsqlookupd(中心管理服务)  4160 4161</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#nsqadmin-展示数据"><span class="nav-number">3.</span> <span class="nav-text">nsqadmin(展示数据)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#nsqd-真正干活的-4150-4151"><span class="nav-number">4.</span> <span class="nav-text">nsqd (真正干活的)  4150 4151</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#消费者"><span class="nav-number">4.1.</span> <span class="nav-text">消费者</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#生产者"><span class="nav-number">4.2.</span> <span class="nav-text">生产者</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#nsq-操作"><span class="nav-number">5.</span> <span class="nav-text">nsq 操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#use"><span class="nav-number">5.1.</span> <span class="nav-text">use</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#go-nsq-使用"><span class="nav-number">6.</span> <span class="nav-text">go-nsq 使用</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/avatar.jpg"
      alt="Levon">
  <p class="site-author-name" itemprop="name">Levon</p>
  <div class="site-description" itemprop="description">Never Give Up</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">127</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        <span class="site-state-item-count">34</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">76</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/unix2dos" title="GitHub &rarr; https://github.com/unix2dos" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:levonfly@gmail.com" title="E-Mail &rarr; mailto:levonfly@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://twitter.com/levonfly" title="Twitter &rarr; https://twitter.com/levonfly" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://weibo.com/l6241425" title="Weibo &rarr; https://weibo.com/l6241425" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Levon</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">507k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">7:41</span>
</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>








  <script src="/js/local-search.js?v=7.4.0"></script>














  

  

  

<script>
  function loadCount() {
    var d = document, s = d.createElement('script');
    s.src = 'https://levonfly.disqus.com/count.js';
    s.id = 'dsq-count-scr';
    (d.head || d.body).appendChild(s);
  }
  // defer loading until the whole page loading is completed
  window.addEventListener('load', loadCount, false);
</script>
<script>
  function disqus_config() {
    this.page.url = "https://unix2dos.github.io/p/17c769c4.html";
    this.page.identifier = "p/17c769c4.html";
    this.page.title = 'nsq介绍和go-nsq使用';};
  function loadComments() {
    if (window.DISQUS) {
      DISQUS.reset({
        reload: true,
        config: disqus_config
      });
    } else {
      var d = document, s = d.createElement('script');
      s.src = 'https://levonfly.disqus.com/embed.js';
      s.setAttribute('data-timestamp', '' + +new Date());
      (d.head || d.body).appendChild(s);
    }
  }
    window.addEventListener('load', loadComments, false);
  
</script>

</body>
</html>
